package com.neusoft.tyut.elm.dao;

 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;

import com.mysql.cj.xdevapi.PreparableStatement;
public class BaseDao {
	private static final String DRIVERNAME="com.mysql.cj.jdbc.Driver";
	private static final String URL="jdbc:mysql://127.0.0.1:3306/elm?serverTimezone=UTC";
	private static final String USERNAME="root";
	private static final String PASWORD="root";
	
	//该段代码完成加载数据库驱动，整个程序只需要加载一次，所以放在静态块中。
    static{
        try{        
            Class.forName( DRIVERNAME);//oracle数据库驱动程序
        }
        catch(ClassNotFoundException e) {
            e.printStackTrace();
        }        
    }  
    
    protected Result query(String sql, Object[] args) {
   	Connection connection = null;
    	PreparedStatement preparedStatement = null;
    	ResultSet resultSet = null;
     
    	try {
    		connection =  getConnection();
    		assert connection!=null;
    		preparedStatement = connection.prepareStatement(sql);
    		if (args!=null && args.length>0) {
				for (int i = 0; i < args.length; i++) {
					preparedStatement.setObject(i+1, args[i] );
				}			
			}
    		resultSet =  preparedStatement.executeQuery();  	    	 
    		return  ResultSupport.toResult(resultSet);	
		} catch (Exception e) {
			System.out.println( "执行失败--> " +  sql  );
			System.out.println( "执行失败--> " +  e.getMessage()  );
		}finally {
			close(resultSet, preparedStatement, connection);
		}    	
		return null;
	} 
    
    
    
    //获取数据库连接方法
    public static Connection getConnection() throws SQLException{
        Connection conn = DriverManager.getConnection(URL,USERNAME,  PASWORD );
        return conn;
    }
    //释放资源(方法重载)
    public static void close(Statement st,Connection conn){
        try{
            if(st != null){
                try{
                	st.close();
                	}
                catch(SQLException e) {                        
                    e.printStackTrace();
                }
            }
        }finally{
            if(conn != null){
                try{
                	conn.close();
                }
                catch(SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }
    public static void close(ResultSet rs,Statement st,Connection conn) {
	    try {
	    	if (rs!=null) {
	    		rs.close();
			}			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    close(st, conn);
    }
}
